// const { axios } = require("./axios.min")
// 请求拦截
axios.interceptors.request.use( 
    (config)=>{  
        config.headers['Authorization'] = 'Bearer' + ' ' + localStorage.getItem('token');
        return config;
    },
    (error)=>{
        return Promise.reject(error)
    }
)
// 响应拦截
axios.interceptors.response.use(
    (res) => {
       return res
    },
    (error) => {
        if(error.response.status==401){
            localStorage.removeItem('token')
            window.location.href = './login.html'
        }
        else if(error.response.status==404){
            alert('访问路径有误')
        }
        else if(error.response.status==500){
            alert('服务器内部错误')
        }
        return Promise.reject(error)
    }
)

function render(dataLis) {
    var str = dataLis.map((item) => {
        return ` <tr>
                    <td>${item.bianhao}</td>
                    <td>${item.bianma}</td>
                    <td>${item.name}</td>
                    <td>${item.phone}</td>
                    <td><span class="${item.status ? '' : 'error'} status">${item.status ? "正常" : "异常"}</span></td>
                    <td>${item.timer}</td>
                    <td><span class="iconfont icon-bianji" id="${item.phone}"></span><span class="iconfont icon-shanchu" data-phone="${item.phone}"></span></td>
                </tr>`
    }).join('')
    document.querySelector("table tbody").innerHTML = str
}
// 渲染用户名
document.querySelector('.username').innerHTML = JSON.parse(localStorage.getItem("userinfo")).name
// 当前页数
var page = 1
// 请求第一页数据
axios.get('/user/list', { params: { page: page, count: 5 } }).then((res) => {
    render(res.data.list)
})
// 点击事件
// 下一页
document.querySelectorAll('.foot span')[1].onclick = function () {
    page++
    axios.get('/user/list', { params: { page: page, count: 5 } }).then((res) => {
        if (page > res.data.totalpage) {
            page = res.data.totalpage
        }
        render(res.data.list)
    })
}
// 上一页
document.querySelectorAll('.foot span')[0].onclick = function () {
    page--
    if (page <= 0) {
        document.querySelectorAll('.foot span')[0].style.disable = true
        page = 1
    }
    axios.get('/user/list', { params: { page: page, count: 5 } }).then((res) => {
        render(res.data.list)
    })
}
// 搜索功能
var searchbox = document.querySelector(".search input")
document.querySelector('.sousuo').onclick = function () {
    axios.get('/user/search', { params: { searchkey: searchbox.value } }).then((res) => {
        render(res.data.list)
    })
}
// 删除功能
var tbody = document.querySelector('tbody')
tbody.onclick = (e) => {
    // 如果目标的类名包含icon-shanchu，就是删除
    if (e.target.classList.contains("icon-shanchu")) {
        // 发请求删除
        axios.post('/user/delete', { phone: e.target.dataset.phone }).then((res) => {
            render(res.data.list)
        })
    }
}
